const execSQL = require('../db/index')
const {formatToLine, formatHumpLineTransfer} = require('../utils/index')
const Router = require('koa-router')
const router = new Router()
//新增用户
//INSERT INTO `rbac`.`user` (`name`, `age`, `sex`, `address`) VALUES ('黎明', 60, '男', '九龙')
//编辑用户
//UPDATE `rbac`.`user` SET `age` = 50, `sex` = '男', `address` = '香港' WHERE `name` = '张学友' AND `id` = 1 AND `age` IS NULL AND `sex` IS NULL AND `address` IS NULL LIMIT 1
//获取商品
router.get('/getRoles', async (ctx) => {
  //{a: '', goodsName: '', pageNum: '1', pageSize: '1'}
  const {pageNum, pageSize, ...filter} = ctx.query
  console.log(pageNum, pageSize, filter, '-------------')
  // filter: {a: '', goodsName:'1'}
  //['a', 'goodsName']
  //!!false === false
  const keyArr = Object.keys(filter).filter((item) => !!filter[item])
  let whereSql = keyArr.length===0?'':' WHERE '

  keyArr.forEach((item, i) => {
    whereSql = `${whereSql}${i===0?'': ' AND '}${formatToLine(item)} = '${filter[item]}'`
  })
  let sqlStr = ''
  if(!pageNum && !pageSize) {
    sqlStr = `SELECT * FROM role${whereSql}`
  } else {
    let start = (pageNum - 1) * pageSize
    let end = pageNum * pageSize
    sqlStr = `SELECT * FROM role${whereSql} LIMIT ${start},${end}`
  }
  
  console.log(whereSql)
  // const [data] = await execSQL(`SELECT * FROM goods${whereSql}`)
  const [{total}] = await execSQL(`SELECT COUNT(*) as total FROM role${whereSql}`)
  const data = await execSQL(sqlStr)
  const list = data.map(item => {
    return formatHumpLineTransfer(item, 'hump')
  })
  
  ctx.body = {
    code: 200,
    data:{
      list,
      total: total
    }
  }
});
router.post('/saveRole', async (ctx) => {
  //sql:INSERT INTO `goods`.`goods` (`goods_name`, `type`, `child_type`, `price`, `number`, `phoneNum`, `goods_picture`, `description`) VALUES ('一加手机', 1, '2', 4000, 200, '18312341234', 'https://consumer.huawei.com/content/dam/huawei-cbg-site/cn/mkt/plp/phones-new/mate-60-pro/kv.jpg', '还凑合')
  const params = ctx.request.body
  const realParam = formatHumpLineTransfer(params, 'toLine')
  let keyStr = Object.keys(realParam).join("`, `")
  let valueStr = Object.values(realParam).join("', '")
  const sqlStr = `INSERT INTO \`goods\`.\`goods\` (\`${keyStr}\`) VALUES ('${valueStr}')` 
  const sqlResult = await execSQL(sqlStr)
  const result = {
    code: 200,
    data: sqlResult.insertId
  }
  ctx.body = result
})
router.get('/deleteRole', async (ctx) => {
  // DELETE FROM `goods`.`goods` WHERE `id` = 4
  const {id} = ctx.query
  const result = execSQL('DELETE FROM `rbac`.`role` WHERE `id` = '+id)
  ctx.body = {
    code: 200,
    data: {id},
    messag: '删除成功'
  }
})
router.post('/getRoleDetail', async (ctx) => {
  const {id} = ctx.request.body
  const res = await execSQL('SELECT * FROM role WHERE id='+id)
  let data = {}
  if(res.length>0) {
    data = res[0]
  }
  ctx.body = {
    code: 200,
    data: formatHumpLineTransfer(data)
  }
})
module.exports = router